package com.nabi.starter.common.tool.tree;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TreeTool {

    /**
     * 转换
     *
     * @param allTrees
     */
    public static   void convert(List<? extends TreeBean> allTrees) {
        convertTree(allTrees, allTrees);
        removeNullChildTree(allTrees);
    }

    /**
     * 递归获取节点
     *
     * @param alls
     * @param roots
     */
    private static void convertTree(List<? extends TreeBean> alls, List<? extends TreeBean> roots) {
        for (TreeBean root : roots) {
            List<TreeBean> child = new ArrayList();
            for (TreeBean all : alls) {
                if (root.levelId().equals(all.parentLevelId())) {
                    child.add(all);
                }
            }
            if (child.size() > 0) {
                root.childs(child);
                convertTree(alls, child);
            }
        }
    }

    /**
     * 移除子节点为空的节点
     *
     * @param alls
     */
    private static void removeNullChildTree(List<? extends TreeBean> alls) {
        Iterator<? extends TreeBean> it = alls.iterator();
        while (it.hasNext()) {
            TreeBean item = it.next();
            Serializable parentLevelId = item.parentLevelId();
            if (parentLevelId != null
                    && ((parentLevelId instanceof Long && (Long) parentLevelId != 0)
                    || (parentLevelId instanceof Integer && (Integer) parentLevelId != 0)
                    || (parentLevelId instanceof String && !"0".equals((String) parentLevelId)))) {
                it.remove();
            }
        }
    }


}
